package com.example.administrator.musicplayer;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.Property;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.Toast;


import com.example.administrator.musicplayer.data.Music;
import com.example.administrator.musicplayer.data.MusicList;
import com.example.administrator.musicplayer.model.PropertyBean;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.view.KeyCharacterMap.load;

public class MainActivity extends AppCompatActivity {

    //显示组件
    private ImageButton bt_Previous;
    private ImageButton bt_PlayOrPause;
    private ImageButton bt_Stop;
    private ImageButton bt_Next;
    private ListView list;

    //歌曲列表对象
    private ArrayList<Music> musicArrayList;
    // 当前歌曲的序号，下标从0开始
    private int number = 0;
    //播放状态
    private int status;
    // 媒体播放类
    private MediaPlayer player = new MediaPlayer();
    //广播接收器
    private StatusChangedReceiver receiver;

    private RelativeLayout root_Layout;






    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViews();
        registerListeners();
        initMusicList();
        initListView();
        checkMusicfile();

        bindStatusChangeReceiver();
        startService(new Intent(this, MusicService.class));
        status = MusicService.COMMAND_STOP;




    }

    private void checkMusicfile() {
        if (musicArrayList.isEmpty()){
            bt_Next.setEnabled(false);
            bt_PlayOrPause.setEnabled(false);
            bt_Previous.setEnabled(false);
            bt_Stop.setEnabled(false);
            Toast.makeText(getApplicationContext(),"当前没有歌曲文件",Toast.LENGTH_SHORT).show();
        }
        else {
            bt_Next.setEnabled(true);
            bt_PlayOrPause.setEnabled(true);
            bt_Previous.setEnabled(true);
            bt_Stop.setEnabled(true);
        }
    }

    //设置适配器并初始化ListView
    private void initListView() {
        List<Map<String, String>> list_map = new ArrayList<Map<String, String>>();
        HashMap<String, String> map;
        SimpleAdapter simpleAdapter;
        for (Music music : musicArrayList){
            map = new HashMap<String, String>();
            map.put("musicName", music.getMusicName());
            map.put("musicArtist" , music.getMusicArtist());
            list_map.add(map);
        }

        String[] from = new String[] {"musicName", "musicArtist"};
        int[] to = {R.id.listview_it01,R.id.listview_it02};

        simpleAdapter = new SimpleAdapter(this, list_map, R.layout.listview, from, to);
        list.setAdapter(simpleAdapter);

    }



    //为显示组件注册监听器
    private void registerListeners() {
        bt_Previous.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                moveNumberToPrevious();
//                play(number);
//                bt_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
            sendBroadcastOnCommand(MusicService.COMMAND_PREVIOUS);

            }

        });

        bt_PlayOrPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (player != null && player.isPlaying()) {
//                    pause();
//                }
//                else {
//                    play(number);
//                    bt_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
//
//                }

                switch (status) {
                    case MusicService.STATUS_PLAYING:
                        sendBroadcastOnCommand(MusicService.COMMAND_PAUSE);
                        break;
                    case MusicService.STATUS_PAUSED:
                        sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                        break;
                    case MusicService.COMMAND_STOP:
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                    default:
                        break;
                }
                }

        });

        bt_Stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                stop();
//                bt_Stop.setBackgroundResource(R.drawable.button_play);
                  sendBroadcastOnCommand(MusicService.COMMAND_STOP);
            }
        });

        bt_Next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                moveNumberToNext();
//                play(number);
//                bt_PlayOrPause.setBackgroundResource(R.drawable.button_play);
                sendBroadcastOnCommand(MusicService.COMMAND_NEXT);

            }
        });
        list.setOnItemClickListener(new AdapterView.OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.i("123","123");
                number = position;
//                play(number);
//                Toast.makeText(MainActivity.this,"123",Toast.LENGTH_SHORT).show();
//                bt_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
                sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
            }
        });
    }


    class StatusChangedReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            status = intent.getIntExtra("status", -1);
            switch (status){
                case MusicService.STATUS_PLAYING:
                    bt_PlayOrPause.setBackgroundResource(R.drawable.pause);
                    break;
                case MusicService.STATUS_PAUSED:
                case MusicService.STATUS_STOPPED:
                    bt_PlayOrPause.setBackgroundResource(R.drawable.play);
                    break;
                case MusicService.STATUS_COMPLETED:
                    sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                    break;
                default:
                    break;
            }
        }
    }


    //初始化音乐列表对象
    private void initMusicList() {
        musicArrayList = MusicList.getMusicList();

        if (musicArrayList.isEmpty()) {
            Cursor mMusicCursor = this.getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    new String[]{
                            MediaStore.Audio.Media.TITLE,
                            MediaStore.Audio.Media.DURATION,
                            MediaStore.Audio.Media.ALBUM,
                            MediaStore.Audio.Media.ARTIST,
                            MediaStore.Audio.Media._ID,
                            MediaStore.Audio.Media.DATA,
                            MediaStore.Audio.Media.DISPLAY_NAME
                    },null,null,
                    MediaStore.Audio.Media.TITLE
            );
            if (mMusicCursor!= null){
                //标题
                int mTitle = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);
                //艺术家
                int mArtist = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);
                //总时长
                int mTotalTime = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION);
                //路径
                int mPath = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);

                for (mMusicCursor.moveToFirst();!mMusicCursor.isAfterLast();mMusicCursor.moveToNext()){
                    String strTitle = mMusicCursor.getString(mTitle);
                    String strArtist = mMusicCursor.getString(mArtist);
                    String strTotoalTime = mMusicCursor.getString(mTotalTime);
                    String strPath = mMusicCursor.getString(mPath);

                    if (strArtist.equals("<unknown"))
                        strArtist = "无艺术家";
                    Music music = new Music(strTitle, strArtist, strPath, strTotoalTime);
                    musicArrayList.add(music);

                }
            }
        }



    }

    //读取音乐文件
    private void load(int number){
        try{
            player.reset();
            player.setDataSource(MusicList.getMusicList().get(number).getMusicPath());
            player.prepare();
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    private void play(int number) {
        //停止当前播放
        if (player != null && player.isPlaying()) {
            player.stop();
        }
        load(number);
        player.start();
    }

    private void pause() {
        if(player.isPlaying()){
            player.pause();
        }
    }

    private void stop(){
        player.stop();
    }

    private void resume(){
        player.start();
    }

    private void replay(){
        player.start();
    }

    //选择上一曲
    private void moveNumberToPrevious() {
        //判断是否到达列表顶端
        if (number == 0) {
            Toast.makeText(MainActivity.this, MainActivity.this.getString(R.string.reach_top), Toast.LENGTH_SHORT).show();

        }
        else {
            --number;
            play(number);
        }

    }

    //选择下一曲
    private void moveNumberToNext(){
        //判断是否到达列表低端
        if ((number) == MusicList.getMusicList().size()-1){
            Toast.makeText(MainActivity.this, MainActivity.this.getString(R.string.reach_bottom),Toast.LENGTH_SHORT).show();
        }
        else {
            ++number;
            play(number);
        }
    }

    private void setTheme (String theme){
        if ("彩色".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_color);
        } else if ("花朵".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_digit_flower);
        } else if ("群山".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_mountain);
        } else if ("小狗".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_running_dog);
        } else if ("冰雪".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_snow);
        } else if ("女孩".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_music_girl);
        } else if ("朦胧".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_blur);
        }
    }

    /*创建菜单*/
    public boolean onCreateOptionsMenu(Menu menu) {
        this.getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

     /*处理菜单点击事件*/
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.menu_theme:
            new AlertDialog.Builder(this)
                    .setTitle("请选择主题").setItems(R.array.theme, new android.content.DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    String theme = PropertyBean.THEMES[which];
//                    Toast.makeText(MainActivity.this, "111", Toast.LENGTH_SHORT).show();
                    MainActivity.this.setTheme(theme);
                    PropertyBean property = null;
                    try {
                        property = new PropertyBean(MainActivity.this);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    property.setAndSaveTheme(theme);
                }

            }).show();
            break;
            case R.id.menu_about:
                new AlertDialog.Builder(MainActivity.this).setTitle("Musicplayer").setMessage(R.string.about).show();
                break;
            case R.id.menu_quit:
                new AlertDialog.Builder(this)
                        .setTitle("提示").
                        setMessage(R.string.quit).setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                        System.exit(0);
                    }
                }).setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                    }
                }).show();
        }
        return super.onOptionsItemSelected(item);
    }



    //绑定广播接收器
    private void bindStatusChangeReceiver(){
        receiver = new StatusChangedReceiver();
        IntentFilter filter = new IntentFilter(MusicService.BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        registerReceiver(receiver, filter);
    }

    private void sendBroadcastOnCommand(int command){
        Intent intent = new Intent(MusicService.BROADCAST_MUSICSERVICE_CONTROL);
        intent.putExtra("command", command);

        //根据不同命令，封装不同的数据
        switch (command){
            case MusicService.COMMAND_PLAY:
                intent.putExtra("number", number);
                break;
            case MusicService.COMMAND_PREVIOUS:
            case MusicService.COMMAND_NEXT:
            case MusicService.COMMAND_PAUSE:
            case MusicService.COMMAND_STOP:
            case MusicService.COMMAND_RESUME:
            default:
                break;
        }
        sendBroadcast(intent);

    }


    //获取显示组件
    private void findViews() {
        bt_Previous = (ImageButton) findViewById(R.id.IB01);
        bt_PlayOrPause = (ImageButton) findViewById(R.id.IB02);
        bt_Stop = (ImageButton) findViewById(R.id.IB03);
        bt_Next = (ImageButton) findViewById(R.id.IB04);
        list = (ListView) findViewById(R.id.listView1);
        root_Layout = (RelativeLayout) findViewById(R.id.activity_main);
    }



    @Override
    public void onStart() {
        super.onStart();

    }

    @Override
    protected void onResume() {
        super.onResume();
        sendBroadcastOnCommand(MusicService.COMMAND_CHECK_IS_PLAYING);
        PropertyBean propety = null;
        try {
            propety = new PropertyBean(MainActivity.this);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String theme = propety.getTheme();

        setTheme(theme);



    }

    @Override
    protected void onDestroy() {
        if (status == MusicService.STATUS_STOPPED){
            stopService(new Intent(this, MusicService.class));
        }
        super.onDestroy();
    }

    @Override
    public void onStop() {
        super.onStop();
    }
}
